from ui import RootPanel, HTML,TabPanel,Grid,TextBox,Composite,TextArea,Button,ListBox,HorizontalPanel,VerticalPanel,DialogBox,Hyperlink
import Window
from History import History
from service import DataService
from RichTextEditor import RichTextEditor
class ArticalItem(Composite):
    def __init__(self,arti,pp):
        self.aid = arti[0]
        self.parent_noti = pp
        btnEdit = Button("Edit",getattr(self,"OnBtnEdit") )
        btnDel = Button("Delete",getattr(self,"OnBtnDelete"))   
        
        self.title = HTML(arti[1],False)
        self.time = HTML(arti[2],False)
        
        self.container = HorizontalPanel()
        self.container.add(self.title)
        self.container.add(self.time)
        self.container.add(btnEdit)
        self.container.add(btnDel)
        
        self.initWidget(self.container)
        self.doPostDel = DataService()
    def OnBtnEdit(self):
        self.parent_noti.ArtiEdit(self.aid)
    def OnBtnDelete(self):
        contents = HorizontalPanel()
        contents.setSpacing(4)
        contents.add(HTML("""Are you sure Delete ?"""))
        contents.add(Button("Yes", getattr(self, "OnDeleteYes")))
        contents.add(Button("No", getattr(self, "OnDeleteNo")))

        self._dialog = DialogBox()
        self._dialog.setHTML('<b>Confirm</b>')
        self._dialog.setWidget(contents)

        left = (Window.getClientWidth() - 200) / 2
        top = (Window.getClientHeight() - 100) / 2
        self._dialog.setPopupPosition(left, top)
        self._dialog.show()
                
        
    def OnDeleteYes(self):
        self.doPostDel.adminPostDel(self.aid,self)
        self._dialog.hide()
    def OnDeleteNo(self):
        self._dialog.hide()
    def onRemoteResponse(self, response, request_info):
        pass
            
            
    def onRemoteError(self, code, message, request_info):
        pass
         
class ArticalManagePanel(Composite):
    def __init__(self,pp):
        self.parent_noti = pp
        self.dogetTitles = DataService()

        
        
        self.list = ListBox()
        self.list.setVisibleItemCount(0)
        self.list.setWidth("100px")
        self.list.addItem("0")
        self.btnRefresh = Button("Refresh",getattr(self,"OnRefresh"))
                
        line1 = HorizontalPanel()
        line1.add(self.list)
        line1.add(self.btnRefresh)
        
        self.artiList = VerticalPanel()
        self.artiList.add(line1)
        
        self.container = VerticalPanel()
        self.container.add(line1)
        self.container.add(self.artiList)
        
        self.initWidget(self.container)
        self.iCurPage = 0
    def OnRefresh(self):
        self.iCurPage = int(self.list.getSelectedIndex())
        self.dogetTitles.adminGetTitles(self.iCurPage,self)
        
    def onRemoteResponse(self, response, request_info):
        ct_arti = response['counter_arti']
        self.list.clear()
        iPages = ct_arti/20+1
        for ii in range(1,iPages):
            self.list.addItem(str(ii))
        lTitles = response['titles']
        self.artiList.clear()
        for arti in lTitles:
            ai = ArticalItem(arti,self.parent_noti)
            self.artiList.add(ai)
            
            
    def onRemoteError(self, code, message, request_info):
        pass
    

class NewPostPanel(Composite):
    def __init__(self):
        self.aid = ''
        self.title = TextBox()
        self.title.setVisibleLength(60)
        self.title.setMaxLength(100)
        
        self.tag = TextBox()
        self.tag.setVisibleLength(60)
        self.tag.setMaxLength(100)

        self.intro = RichTextEditor()
        self.intro.setSize("600px", "500px")
        
        self.content = RichTextEditor()
        self.content.setSize("600px", "600px")

        self.submit = Button("Submit")
        self.submit.addClickListener(getattr(self,"OnSubmit"))
        
        self.btnClear = Button("Clear")
        self.btnClear.addClickListener(getattr(self,"OnClear") )
        
        hpBtnAction = HorizontalPanel()
        hpBtnAction.add(self.submit)
        hpBtnAction.add(self.btnClear)
                                 
        grid = Grid(5,2)
        
        grid.setText(0, 0, "Title")
        grid.setWidget(0, 1, self.title)
        
        grid.setText(1, 0, "tags")
        grid.setWidget(1, 1, self.tag)
        
        grid.setText(2,0,"Intro")
        grid.setWidget(2, 1, self.intro)

        grid.setText(3, 0, "Content")
        grid.setWidget(3, 1, self.content)


        grid.setText(4,0,"Action")
        grid.setWidget(4, 1, hpBtnAction)

        self.initWidget(grid)
        self.doSubmit = DataService()
        self.doEditGet = DataService()
        
    def OnSubmit(self):
        usTitle = self.title.getText()
        usTags = self.tag.getText()
        usIntro =self.intro.getHTML()
        usContent = self.content.getHTML()
        
        self.doSubmit.adminNewPost(self.aid,usTitle,usTags,usIntro,usContent)
    def Edit(self,id):
        self.aid = id
        self.doEditGet.adminGetArtical(self.aid,self) 
        
    def onRemoteResponse(self, response, request_info):
        self.title.setText(response[0])
        self.tag.setText(response[1])
        self.intro.setHTML(response[2])
        self.content.setHTML(response[3])

    def onRemoteError(self, code, message, request_info):
        self.sel.addItem("err")
    
    def OnClear(self):
        self.aid = ''
        self.title.setText('')
        self.tag.setText('')
        self.intro.setHTML('')
        self.content.setHTML('')
class ConfigPanel(Composite):
    def __init__(self):
        self.doConfig =  DataService()
        
        self.newTextBox = TextBox()
        self.newTextBox.setSize("800px", "60px")
        
        line1 = HorizontalPanel()
        line1.add(Button("Refresh",getattr(self,"OnClickRefresh")) )
        line1.add(Button("Update",getattr(self,"OnClickUpdate")) )
        line1.add(Button("Add New",getattr(self,"OnClickNew")) )
        line1.add(self.newTextBox)
        
        self.sidebarList = VerticalPanel()
        
        container = VerticalPanel()
        container.add(line1)
        container.add(self.sidebarList)
        self.initWidget(container)
    def OnClickRefresh(self):
        dSend = {}
        dSend['type']='get'
        dSend['content']=[]
        self.doConfig.adminSidebars(dSend,self)
    def OnClickUpdate(self):
        dSend = {}
        dSend['type']='update'
        lContent=[]
        for sidebar in self.sidebarList:
            if sidebar.getText():
                lContent.append(sidebar.getText() )
        dSend['content']=lContent
        self.doConfig.adminSidebars(dSend,self)
    def OnClickNew(self):
        dSend = {}
        dSend['type']='new'
        lContent=[]
        lContent.append(self.newTextBox.getText() )
        dSend['content']=lContent
        self.doConfig.adminSidebars(dSend,self)        
    def onRemoteResponse(self, response, request_info):
        atype = response['type']
        if atype == 'get':
            listContent = response['content']
            self.sidebarList.clear()
            for sidebar in listContent:
                sbTextBox = TextBox()
                sbTextBox.setSize("800px", "60px")
                self.sidebarList.add(sbTextBox)
                sbTextBox.setText(sidebar)
    def onRemoteError(self, code, message, request_info):
        pass
    
class admin:
    def onModuleLoad(self):
        self.doAdmin = DataService()
        loc = Window.getLocation()
        
        self.hLogin = HTML("Login")
        self.hLogout = HTML("Logout")
        hpLogin = HorizontalPanel()
        hpLogin.add(self.hLogin )
        hpLogin.add(self.hLogout)
        
        self.postPanel = NewPostPanel()
        self.mainPanel = ArticalManagePanel(self)
        
        self.tabs = TabPanel()
        self.tabs.setWidth("100%")
        self.tabs.add(self.mainPanel, "Home")
        self.tabs.add(self.postPanel, "New Post")
        self.tabs.add(ConfigPanel(), "Config")

        container = VerticalPanel()
        container.add(hpLogin)
        container.add(self.tabs)
        RootPanel().add(container)
        
        self.doAdmin.adminGetLoginUrl(loc.getPathname(),self)
    def ArtiEdit(self,id):
        self.tabs.selectTab(1)
        self.postPanel.Edit(id)
    def onRemoteResponse(self, response, request_info):
        #console.log(response)
        self.hLogin.setHTML("""<a href=" """ + response[0] + """ ">""" + """login</a> """)
        self.hLogout.setHTML("""<a href=" """ + response[1] + """ ">""" + """logout</a> """)
    def onRemoteError(self, code, message, request_info):
        pass
        